<?php
/**
 * Widget To Save the Query
 * It will display a popup to give a name to your query
 * and save all criteria as in json format
 *
 * @author Xavier VILAIN
 * @package QueryBuilder
 * @license
 */
use Fox\Core\Errors;
use Fox\Query;
use Fox\Html\Block;
use Fox\Query\Messages;
use Fox\Html\Input;
use Fox\Html\Screen;
use Fox\Html\CheckBox;
use Fox\Popup;
$xview = Xview::instance();
$jsonFields = $xview->val('jsondata');
if(!empty($jsonFields)) {
	$jsonFields = preg_replace("/\"/","'",$jsonFields);
	unset($_GET['jsondata']);

}
$location = $xview->val('location');
if(!empty($location)) {
	$location = preg_replace("/\"/","'",$location);
	unset($_GET['location']);
}
$screen = new Screen('sQueryManager','save',null,true);
$screen->buttonBarClass('text-center');
$block = new Block('bQueryManager');
$block->noLegend();
$block->add(new Input(array('query_label','label'),true));
$block->add(new CheckBox('private',true));
$block->add(new Input('jsonfields',false,$jsonFields))->hidden();
$block->add(new Input('target_uri',false,$location))->hidden();
$screen->add($block);
if($screen->submitted()) {
	$inputs = $screen->get();
	if(!$screen->errors()) {
		try {
			$query = new Query();
			$inputs['label'] = $inputs['label'];
			$query->setFields($inputs);
			$query->create();
			echo Msg(Messages::BUNDLE,Messages::MSG_SUCCESS_SAVED,$inputs['label']);
			exit;
		}
		catch (Fox\Object\Exception\Save $e) {
			Errors::pushMessage($e);
		}
	}
}
$popup = new Popup('pQueryManager',Msg(Messages::BUNDLE,Messages::TITLE_CREATE_A_QUERY),$screen,550);
if($screen->errors()) {
	echo Xview::instance()->messages();
}
else {
	echo $popup->display();
}
